// 相关文章
const getCoursesApi = api.getCourses;
const getOutlineApi =api.getOutlines;
const getOutlineByIdApi = api.getOutlineById;
const saveArticleApi = api.saveArticle;

let ArticleFormVue = new Vue({
    el: '#article_form',
    data: {
        grade: [{id: 1, name: '小学'},
            {id: 2, name: '初中'},
            {id: 3, name: '高中'},
            {id: 4, name: '大学'},],
        courses: [],
        outlines: [],
        selectedOutline:{id:6},
        selectedOutlineDetail:{}
    },
    created: function () {
        // $.ajax({
        //     url: '/api/grade',
        //     type: 'get',
        //     success: (res) => {
        //         this.grade = res.data;
        //     }
        // })
    },
    methods: {
        async searchCourse(key, form) {
            // 获取年级
            var gradeId = $('#grade select').val();
            if (gradeId == '') {
                layuiUtil.msg.msgWarning('情选择年级')
                // layer.msg("情选择年级", {"icon": 2})
                return;
            }
            // 获取课程
            var res = await getCoursesApi({key, gradeId})
            this.courses = res.data;
            let dd = `<dd lay-value="" class="layui-select-tips layui-this">直接选择或搜索选择</dd>`;
            let opt = `<option value="" >直接选择或搜索选择</option>`;
            if (res.data != null && this.courses.length != 0) {
                let select = $('#course select')
                // select.find('option.expected').siblings().remove();
                for (var i = 0; i < this.courses.length; i++) {
                    opt += `<option value="${this.courses[i].id}">${this.courses[i].name}</option>`;
                    // dd += `<dd lay-value="${this.courses[i].id}">${this.courses[i].name}</dd>`;
                }
                $('#course select').html(opt);
                // $('#course select').next().children().eq(1).html(dd);
                form.render('select', 'course');
                $('#course>div').addClass('layui-form-selected');
                $('#course input').val(key).focus()
            }
        },
        async setOutline (courseId, form) {
            var res = await getOutlineApi({courseId})
            this.outlines = res.data;
            let opt = `<option value="" >请选择</option>`;
            if (res.data.length > 0) {
                for (let i = 0; i < res.data.length; i++) {
                    opt += `<option value="${this.outlines[i].id}">${this.outlines[i].name}</option>`;
                }
                $('#outline select').html(opt);
                form.render('select', 'outline')
            }
        }
    }
})


layui.use(['element', 'tree', 'layer', 'form', 'upload', 'layedit'], function () {
    var $ = layui.jquery, tree = layui.tree, form = layui.form, layedit = layui.layedit;
    var element = layui.element;

    // 搜索课程
    var timer = null;
    $(document).on('input propertychange', '#course input', function (e) {
        if (timer == null) {
            timer = window.setTimeout(() => {
                ArticleFormVue.searchCourse($(this).val(), form);
            }, 500);
        } else {
            window.clearTimeout(timer);
            timer = window.setTimeout(() => {
                ArticleFormVue.searchCourse($(this).val(), form);
            }, 500);
        }

    });

    form.on("select(course)", (data) => {
        if (data.value == '') {
            return;
        }
        ArticleFormVue.setOutline(data.value, form)

    })



    // 加载大纲知识点
    form.on('select(outline)', async function (data) {
        if (data.value == '') {
            return;
        }
        $('#outlineDetailLoad').show();
        //
        let outlineId = data.value;
        // 获取大纲
        var res = await getOutlineByIdApi(outlineId);
        if(res.code==0){
            console.log(res.data.content)
            // 加载知识点树
            $('#outline_tree').html('')
            layui.tree({
                elem: '#outline_tree' //传入元素选择器
                , nodes:res.data
                ,click: function(node){
                    console.log(node) //node即为当前点击的节点数据
                    if(node.children == undefined){
                        ArticleFormVue.selectedOutlineDetail = node;
                    }
                }
            });
            $('#outlineDetailLoad').hide();
        }
    })

    $('#submit_article').on('click', function () {
        // title
        var title = $('#title').val();
        var outlineId = $('#outline select').val();
        if(ArticleFormVue.selectedOutlineDetail.num == undefined){
            layer.msg('请选择知识点', {icon: 5})
            return;
        }
        if (title == '') {
            layer.msg('请输入标题', {icon: 5})
            return;
        }
        if (outlineId == '') {
            layer.msg('请选择大纲', {icon: 5})
            return;
        }
        console.log(title)
        console.log(outlineId)
        console.log(quill.root.innerHTML)

        layer.confirm('是否要上传?', {icon: 3, title: '提示'}, async function (index) {
            //do something
            var data = {title: title, content: quill.root.innerHTML,
                'outlineDetail.outlineId':outlineId,   // 根据outlineId 和num可以定位大纲细节
                'outlineDetail.num':ArticleFormVue.selectedOutlineDetail.num,
            };
            const res = await saveArticleApi(data)
            if(res.code == 0){
                layer.msg('保存成功', {icon: 6})
                window.location.href = '/teacher/article/details.html?id=' + res.data.id;
            }else{
                layer.msg('系统繁忙', {icon: 5})
            }
            layer.close(index);
        });
    });


    // loadOptions("grade", "subject");

});

